const db = require('../config/database');
const logger = require('../utils/logger');

class CustomerServiceController {
  // 用户发送消息给客服
  async sendMessage(req, res) {
    try {
      const { message_type = 'text', content } = req.body;
      const user = req.user;

      if (!content) {
        return res.json({
          success: false,
          message: '消息内容不能为空'
        });
      }

      const userId = user ? user.id : null;
      // openid字段保留用于兼容历史数据，但不再作为业务逻辑依据
      const openid = user ? (user.openid || null) : null;

      const [result] = await db.query(
        `INSERT INTO customer_service_messages (user_id, openid, message_type, content, is_from_user, created_at) 
         VALUES (?, ?, ?, ?, 1, NOW())`,
        [userId, openid, message_type, content]
      );

      logger.info('用户发送客服消息', { messageId: result.insertId, userId });

      res.json({
        success: true,
        message: '消息发送成功',
        data: { id: result.insertId }
      });
    } catch (error) {
      logger.error('发送消息失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 用户获取自己的聊天记录
  async getUserMessages(req, res) {
    try {
      const { page = 1, pageSize = 20 } = req.query;
      const offset = (page - 1) * pageSize;
      const user = req.user;

      let sql;
      let params;

      if (user && user.id) {
        // 登录用户（使用userId）
        sql = `SELECT * FROM customer_service_messages 
               WHERE user_id = ?
               ORDER BY created_at DESC LIMIT ? OFFSET ?`;
        params = [user.id, parseInt(pageSize), offset];
      } else {
        return res.json({
          success: false,
          message: '请先登录'
        });
      }

      const [messages] = await db.query(sql, params);

      // 获取总数
      const countSql = 'SELECT COUNT(*) as total FROM customer_service_messages WHERE user_id = ?';
      const [countResult] = await db.query(countSql, [user.id]);

      res.json({
        success: true,
        data: {
          list: messages.reverse(), // 倒序排列，最新的在底部
          total: countResult[0].total,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        }
      });
    } catch (error) {
      logger.error('获取聊天记录失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 客服回复消息（后台管理）
  async replyMessage(req, res) {
    try {
      const { user_id, message_type = 'text', content } = req.body;

      if (!content) {
        return res.json({
          success: false,
          message: '消息内容不能为空'
        });
      }

      if (!user_id) {
        return res.json({
          success: false,
          message: '用户ID不能为空'
        });
      }

      const [result] = await db.query(
        `INSERT INTO customer_service_messages (user_id, openid, message_type, content, is_from_user, created_at) 
         VALUES (?, ?, ?, ?, 0, NOW())`,
        [user_id, null, message_type, content] // openid设为null，仅使用user_id
      );

      logger.success('客服回复消息', { messageId: result.insertId });

      res.json({
        success: true,
        message: '回复成功',
        data: { id: result.insertId }
      });
    } catch (error) {
      logger.error('客服回复失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 获取所有客服消息（后台管理）
  async getAllMessages(req, res) {
    try {
      const { page = 1, pageSize = 20, user_id, is_read } = req.query;
      const offset = (page - 1) * pageSize;

      let sql = 'SELECT * FROM customer_service_messages WHERE 1=1';
      const params = [];

      if (user_id) {
        sql += ' AND user_id = ?';
        params.push(user_id);
      }

      if (is_read !== undefined) {
        sql += ' AND is_read = ?';
        params.push(is_read);
      }

      sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
      params.push(parseInt(pageSize), offset);

      const [messages] = await db.query(sql, params);

      // 获取总数
      let countSql = 'SELECT COUNT(*) as total FROM customer_service_messages WHERE 1=1';
      const countParams = [];

      if (user_id) {
        countSql += ' AND user_id = ?';
        countParams.push(user_id);
      }

      if (is_read !== undefined) {
        countSql += ' AND is_read = ?';
        countParams.push(is_read);
      }

      const [countResult] = await db.query(countSql, countParams);

      res.json({
        success: true,
        data: {
          list: messages,
          total: countResult[0].total,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        }
      });
    } catch (error) {
      logger.error('获取客服消息失败（后台）', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 标记消息为已读
  async markAsRead(req, res) {
    try {
      const { ids } = req.body;

      if (!ids || !Array.isArray(ids) || ids.length === 0) {
        return res.json({
          success: false,
          message: '消息ID不能为空'
        });
      }

      const placeholders = ids.map(() => '?').join(',');
      await db.query(
        `UPDATE customer_service_messages SET is_read = 1 WHERE id IN (${placeholders})`,
        ids
      );

      logger.success('标记消息已读', { count: ids.length });

      res.json({
        success: true,
        message: '标记成功'
      });
    } catch (error) {
      logger.error('标记消息已读失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 获取客服配置（联系方式）
  async getCustomerServiceConfig(req, res) {
    try {
      const [configs] = await db.query(
        `SELECT config_key, config_value FROM system_config 
         WHERE config_key IN (
           'customer_service_name',
           'customer_service_phone',
           'customer_service_wechat',
           'customer_service_email',
           'customer_service_qq',
           'customer_service_qr',
           'customer_service_work_time'
         )`
      );

      const configMap = {};
      configs.forEach(item => {
        configMap[item.config_key] = item.config_value;
      });

      res.json({
        success: true,
        data: configMap
      });
    } catch (error) {
      logger.error('获取客服配置失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }
}

module.exports = new CustomerServiceController();

